import config from "@/utils/config.js"
/**
 * 后台API请求
 * @param {*对象参数} params 
 * @param {*回调函数} callback 
 */
export class Request {
	static HOST = config.debug ? config.hostCfg.develop.host : config.hostCfg.master.host;

	constructor(url = null, data) {
		this.url = url;
	}
	request(method = Object, params = Object, callback) {

		uni.request({
			url: `${Request.HOST}${this.url}`, //仅为示例，并非真实接口地址。
			method: method(),
			data: params(),
			// 自定义请求头信息
			header : { 'content-type':'application/x-www-form-urlencoded'},
			success: (setData) => {
				//接口成功回调
				function success() {
					callback(setData);
				}
				//HTTP状态码
				switch (setData.statusCode) {
					case 500:
						this.showToast('内部服务器错误', 'none', () => {
							setTimeout(() => {
								//报错跳转首页，重新登陆
								uni.switchTab({
									url: '/pages/index/index',
									complete: (params) => {
										console.log('已重新加载/pages/index/index路径')
									},
								});
							}, 1000); //rest：param1, param2, ..., paramN 等附加参数，它们会作为参数传递给回调函数
						});
						break;
					case 404:
						this.showToast('请求的资源不存在');
						break;
					case 401:
						this.showToast('网络出错');
						break;
					case 200:
						new success();
						break;
					default:
				}
			}
		});
	}

	/**
	 * 显示showToast
	 */
	showToast(title = '', icon = 'none', setTimeout = Object) {
		uni.showToast({
			title: title,
			position: 'center', //position 值说明（仅App生效）
			icon: icon,
			duration: 1000,
			mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
		});
		//接口报错，延迟跳转首页
		setTimeout();
	}
	
	/**
	 * 用户还没有注册跳转登陆页面
	 */
	GoToLoginPage(){
		this.showToast('当前是游客身份','none',function(){
			setTimeout(function(){
				uni.switchTab({
				    url: '/pages/mine/mine'
				});
			},2001);
		});
	}
	/**
	 * @author zn
	 */
	getHostCfg(){
		return config.debug ? config.hostCfg.develop : config.hostCfg.master
	}
	
	/**
	 * 登录
	 * @author zn
	 */
	getLogin(app, callback){
		uni.login({
			success: (res) => {
				//获取openid,用户信息接口
				new Request('User_Login/GetUserOpendInfoAndRegister').request(
					() => {
						return 'POST';
					},
					() => {
						return {
							code: res.code,
							DevelopVersion: app.globalData.DevelopVersion,
							project: app.globalData.project,
						}
					},
					(res) => {
						app.globalData.Logincode = res.data.data.LoginCode
						app.globalData.openid = res.data.data.openid
						if(callback != undefined){
							callback(app);
						}
					}
				);
			},
			fail: (err) => {
				console.log(err)
				console.log('失败')
			}
		});
	}
	/**
	 * 图片路径
	 */
	getImageUrl(){
		return config.localImge;
	}
}